//
//  ModifyDataViewController.m
//  HeSiad
//
//  Created by ZC on 15/4/30.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "ModifyDataViewController.h"
#import "AppDelegate.h"
#import "leftViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#define personalDataURL @"http://192.168.1.110:8888/hesaid/index.php/Hesaid/PersonalCenter"
#define headPortraitURL @"http://192.168.1.110:8888/hesaid/index.php/Hesaid/uploadingheadPortrait"
@interface ModifyDataViewController (){
    NSDictionary *modifyDic;
    NSMutableArray *modifyArray;
    AppDelegate *app;
    
    
}

@end

@implementation ModifyDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    modifyArray = [NSMutableArray array];
    
    //性别选择
    [self.sex addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.headportraitImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTapped)];
    [self.headportraitImage addGestureRecognizer:singleTap];//点击图片事件
    [self loading];
    
    // Do any additional setup after loading the view from its nib.
}
-(void)photoTapped{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照",@"本地相册",nil];
    [actionSheet showInView:self.view];
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://照相机
        {   if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"NO Camera" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
            
        }
            break;
            
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)image {
    
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(85, 85)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    
    UIImage *Image=[UIImage imageWithContentsOfFile:imageFilePath];//写入文件
    self.headportraitImage.image=Image;
    NSData *data = UIImageJPEGRepresentation(self.headportraitImage.image, 1.0);
    NSURL *url=[NSURL URLWithString:headPortraitURL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self;
    [request setData:data  withFileName:@"tmp.jpg" andContentType:@"image/jpg" forKey:@"headPortrait"];
    [request setPostValue:app.user_id forKey:@"user_id"];
    [request setTag:3];
    [request startAsynchronous];
}
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
    NSString *json=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",json);
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
    NSString *str=dic[@"key"];
    
    if ([str isEqualToString:@"success"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"touxiangAPI" object:nil];
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}
-(void)loading{
    NSURL *url=[NSURL URLWithString:personalDataURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        modifyArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:modifyArray waitUntilDone:YES];
        for (NSDictionary *dic in modifyArray) {
            self.phone.text= [NSString stringWithFormat:@"%@",dic[@"user_phone"]];
            self.sexLabel.text = [NSString stringWithFormat:@"%@",dic[@"user_sex"]];
            NSString *headportrait = [NSString stringWithFormat:@"%@",dic[@"user_HeadPortrait"]];
            NSURL *url=[NSURL URLWithString:headportrait];
            self.headportraitImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        
        }

        
    }];
    
}

-(void)refreshData{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 选择控制器的点击事件
-(void)segmentAction:(UISegmentedControl *)Sex{
    
    NSInteger Index = Sex.selectedSegmentIndex;
    switch (Index) {
        case 0:
            self.sexLabel.text=@"男";
            break;
        case 1:
            self.sexLabel.text=@"女";
            break;
        default:
            break;
    }
}

- (IBAction)modify:(id)sender {
    
    leftViewController *leftVC=[[leftViewController alloc]initWithNibName:@"leftViewController" bundle:nil];
    [self.navigationController pushViewController:leftVC animated:YES];
}
@end
